import * as echarts from 'echarts';
import {LitElement, html, TemplateResult} from 'lit';
import {customElement, property} from "lit/decorators.js";
import style from '../echarts.css.ts';

export interface BarProps {
    chartId?: string;
    width?: string;
    height?: string;
    tooltip?: object;
    legend?: object;
    grid?: object;
    barWidth?: string;
    axisTick?: object;
    showBarBackground?: boolean;
    backgroundStyle?: object;
    xAxisData?: string[];
    seriesData?: any[][] | any[];
}

@customElement('lit-bar')
export class LitBar extends LitElement {
    @property({ type: String }) chartId: string = 'lit-bar-chart';
    @property({ type: String }) width: string = '600px';
    @property({ type: String }) height: string = '400px';
    @property({ type: Object }) tooltip: any = undefined;
    @property({ type: Object }) legend: any = undefined;
    @property({ type: Object }) grid: any = undefined;
    @property({ type: String }) barWidth: string | undefined = undefined;
    @property({ type: Object }) axisTick: any = undefined;
    @property({ type: Boolean }) showBarBackground: boolean = false;
    @property({ type: Object }) backgroundStyle: any = undefined;
    @property({ type: Array }) xAxisData: string[] = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    @property({ type: Array }) seriesData: any[][] = [[120, 200, 150, 80, 70, 110, 130]];

    getSeries(): any[] {
        return this.seriesData.map((data, index) => ({
            name: this.xAxisData[index] || undefined,
            type: 'bar',
            barWidth: this.barWidth,
            showBackground: this.showBarBackground,
            backgroundStyle: this.backgroundStyle,
            data: data,
        }));
    }

    option: echarts.EChartsOption = {
        tooltip: this.tooltip,
        legend: this.legend,
        grid: this.grid,
        xAxis: {
            type: 'category',
            data: this.xAxisData,
            axisTick: this.axisTick,
        },
        yAxis: {
            type: 'value'
        },
        series: this.getSeries(),
    };

    static styles = style;

    updated() {
        this.option.tooltip = this.tooltip;
        this.option.legend = this.legend;
        this.option.grid = this.grid;
        (this.option.xAxis as any).axisTick = this.axisTick;
        (this.option.xAxis as any).data = this.xAxisData;
        this.option.series = this.getSeries();
        this.firstUpdated();
    }

    firstUpdated() {
        const chart = echarts.init(this.shadowRoot!.getElementById(this.chartId)!);
        chart.setOption(this.option);
    }

    render(): TemplateResult {
        return html`<div id="${this.chartId}" style="width: ${this.width}; height: ${this.height};"></div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'lit-bar': LitBar;
    }
}